package com.spc.boot.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.spc.boot.admin.entity.SysUser;
import com.spc.boot.admin.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.UUID;

@Controller
public class AccountController {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    ISysUserService iSysUserService;

    //注册账号
    @GetMapping("/account/register")
    public String register(){
        return "/account/register";
    }


    //测试网页
    @RequestMapping("/account/homepage")
    public String homepage(HttpServletRequest request, HttpServletResponse response) throws Exception {
            return  "homepage";
    }

    //注册账号
    @RequestMapping("/account/doRegister")
    public String doRegister(HttpServletRequest request, HttpServletResponse response) throws Exception {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if ( StringUtils.isEmpty(username)
                || StringUtils.isEmpty(password)) {
            throw new Exception("请填写帐号密码、用户姓名。");
            //resultHolder.get().setMessage("请填写帐号密码、用户姓名。");
        }

        if (iSysUserService.count(new QueryWrapper<SysUser>().eq("LOGIN_ID", username)) > 0) {
            //resultHolder.get().setMessage("登录帐号已经存在。");
            throw new Exception("登录帐号已经存在。");
        }

        SysUser sysUser = new SysUser();
        sysUser.setUserId(UUID.randomUUID().toString());
        sysUser.setLoginId(username);
        sysUser.setPassword(passwordEncoder.encode(password));
        sysUser.setUserName("小刘子");
        sysUser.setLoginCount(1);
        sysUser.setIsEnabled(true);
        sysUser.setIsLocked(false);
        sysUser.setIsDeleted(false);
        sysUser.setCreatedDate(LocalDateTime.now());
        iSysUserService.save(sysUser);

        //注册成功,跳转登录页面
        return "redirect:/";
    }

}
